package repository

import (
	"github.com/redis/go-redis/v9"
	"good.house/internal/model"
	"gorm.io/gorm"
)

type IPublishRepository interface {
	Create(*model.Publish) error
	Update(*model.Publish) error
}

type PublishRepository struct {
	db  *gorm.DB
	rdb *redis.Client
}

func NewPublishRepository(db *gorm.DB, rdb *redis.Client) *PublishRepository {
	return &PublishRepository{
		db:  db,
		rdb: rdb,
	}
}

func (p *PublishRepository) Create(publish *model.Publish) error {
	err := p.db.Transaction(func(db *gorm.DB) error {
		if err := p.db.Create(publish).Error; err != nil {
			return err
		}

		if len(publish.Resource) == 0 {
			return nil
		}

		for i := range publish.Resource {
			publish.Resource[i].PublishID = publish.ID
		}

		if err := p.db.Create(&publish.Resource).Error; err != nil {
			return err
		}

		return nil
	})

	return err
}

func (p *PublishRepository) Update(publish *model.Publish) error {
	err := p.db.Transaction(func(db *gorm.DB) error {
		// 先保存到publish表
		if err := db.Save(publish).Error; err != nil {
			return err
		}

		// 永久删除resouce_data表中对应publishid对应的数据
		db.Unscoped().Where("publish_id = ?", publish.ID).Delete(&model.ResourceData{})

		if len(publish.Resource) == 0 {
			return nil
		}

		if err := db.Create(publish.Resource).Error; err != nil {
			return nil
		}

		return nil
	})

	return err
}
